<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录组件 -->
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- tab导航切换 -->
      <section class="navs">
        <span :class="{ active: isShowLogin }" @click="isShowLogin = true">手机号登录</span>
        <span :class="{ active: !isShowLogin }" @click="showQrCode">微信扫码登录</span>
      </section>
      <div class="content">
        <!-- 手机号登录 -->
        <div class="phonelogin" v-show="isShowLogin">
          <!-- 表单布局 -->
          <div class="row">
            <input type="text" placeholder="请输入手机号" v-model.number.trim="phoneNumber" />
          </div>
          <!-- 拼图验证滑块 -->
          <div class="row">
            <slide-verify :l="42" :r="20" :w="362" :h="140" @success="onSuccess" @fail="onFail" @refresh="onRefresh" :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg" :imgs="imgArr" :accuracy="num"></slide-verify>
          </div>
          <!-- 验证码 -->
          <div class="row">
            <input type="text" placeholder="请输入短信验证码" v-model="dxcode" @keydown.enter="submitFn" />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">获取验证码</button>
            <button class="btn btncode" v-show="isShowCount">{{ count }}s</button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 -->
        <div class="qrlogin" v-show="!isShowLogin" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex'
import { validatePhoneNumber } from '@/utils'
import { SendSMSAPI, PhoneReginAPI, BindWXAPI } from '@/request/api'
export default {
  data() {
    return {
      isShowLogin: true,
      msg: '向右滑动',
      imgArr: [require('@/assets/images/integral-01.9386d4bf.png'), require('@/assets/images/integral-02.150d92a1.png'), require('@/assets/images/integral-03.9870f3f1.png'), require('@/assets/images/integral-04.afadcbdf.png')],
      num: 10,
      // 手机号码
      phoneNumber: '',
      // 倒计时
      count: 60,
      // 是否显示倒计时数字
      isShowCount: false,
      // 短信验证码
      dxcode: ''
    }
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: 'showModal/changeIsShowLoginModal',
      changeIsLogined: 'loginStatus/changeIsLogined',
      changeIsShowToast: 'showToast/changeIsShowToast'
    }),
    ...mapActions({
      asyncChangeIsShowToast: 'showToast/asyncChangeIsShowToast',
      asyncChangeUserInfo: 'userInfo/asyncChangeUserInfo'
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1)
      this.msg = 'login success, 耗时 ' + ms + 's'
    },
    // 拼图失败
    onFail() {
      this.onRefresh() // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = '再试一次'
    },
    // 验证手机号 和 滑块验证码
    toVerify() {
      // 1.判断手机号不能为空
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert('请输入正确的手机号码')
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: '请输入正确的手机号码',
          type: 'danger'
        })
        return
      }
      // 2.判断滑块验证码滑动正确
      if (this.msg == '向右滑动' || this.msg == '再试一次') {
        // alert('请滑动滑块验证码')
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: '请滑动滑块验证码',
          type: 'danger'
        })
        return
      }
      return true
    },
    // 获取验证码
    async getCode() {
      // 1.判断手机号不能为空
      // 2.判断滑块验证码滑动正确
      if (!this.toVerify()) return
      // 3.获取验证码（调用后端接口）
      let res = await SendSMSAPI(this.phoneNumber)
      // 处理报错
      if (!res) return
      // 倒计时
      if (res.code == 0) {
        this.isShowCount = true
        let timer = setInterval(() => {
          this.count--
          if (this.count <= 0) {
            clearInterval(timer)
            this.count = 60
            this.isShowCount = false
          }
        }, 1000)
      }
    },
    // 登录功能
    async submitFn() {
      // 1.判断手机号不能为空如果为空
      // 2.判断滑块验证码滑动正确如果不正确
      if (!this.toVerify()) return
      // 3.判断短信验证码是否输入正确如果不正确
      if (!this.dxcode || this.dxcode.length != 4) {
        // alert('验证码错误')
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: '验证码错误',
          type: 'danger'
        })
        return
      }
      // 4.发送登录请求(普通登录请求/关联微信的登录[uuid] BindWXAPI)
      let uuid = localStorage.getItem('uuid')
      let res = null
      if (uuid) {
        // 关联微信的登录
        res = await BindWXAPI({
          phone: this.phoneNumber,
          verifyCode: this.dxcode,
          uuid
        })
      } else {
        res = await PhoneReginAPI(this.dxcode, this.phoneNumber)
      }
      // console.log(res)
      if (!res) return
      if (res.code == 0) {
        // alert('登录成功')
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: '登录成功',
          type: 'success'
        })
        // 本地存储token
        localStorage.setItem('x-auth-token', res['x-auth-token'])
        // 自动关闭掉登录模态框
        this.changeIsShowLoginModal(false)
        // 4.topbar 中登录按钮要变成购物车按钮。
        this.changeIsLogined(true)
        // 5.删除uuid
        localStorage.removeItem('uuid')
        // 6.登录成功后：获取用户信息
        this.asyncChangeUserInfo()
      }
    },
    // 切换功能,显示二维码
    showQrCode() {
      this.isShowLogin = false

      let _this = this
      new WxLogin({
        id: 'weixin',
        appid: 'wx67cfaf9e3ad31a0d', // 这个appid要填死
        scope: 'snsapi_login',
        // 扫码成功后重定向的接口
        redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
        // state填写编码后的url
        state: encodeURIComponent(window.btoa('http://127.0.0.1:8080' + _this.$route.path)),
        // 调用样式文件
        // 1. 编写css
        // 2. 将css转换为base64,将地址复制进来。
        // (wxLoginStyle终端下面，运行 node data-url.js，复制第一行放到href)
        href: 'data:text/css;base64,LmltcG93ZXJCb3ggLmluZm8sDQouaW1wb3dlckJveCAudGl0bGUgew0KICBkaXNwbGF5OiBub25lOw0KfQ0K'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background-image: url('@/assets/images/login-box-bg.png');
    .close {
      position: absolute;
      right: 60px;
      top: 20px;
      width: 22px;
      height: 22px;
      background-image: url('@/assets/images/close.png');
      cursor: pointer;
    }
    .navs {
      font-size: 18px;
      padding-top: 40px;
      text-align: center;
      span {
        text-decoration: none;
        color: #959595;
        padding: 0 15px;
        cursor: pointer;
        &.active {
          color: #000;
        }
        &:first-child {
          border-right: 1px solid #ccc;
        }
      }
    }
    .content {
      width: 355px;
      margin: 40px auto 20px;
      text-align: center;
      font-size: 14px;
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          input {
            height: 50px;
            flex: 1;
            text-indent: 1em;
          }
          .btn {
            background-color: #0a328e;
            color: #fff;
            cursor: pointer;
          }
          .btncode {
            width: 100px;
            margin-left: 10px;
            padding: 0 10px;
          }
          .btnlogin {
            width: 100%;
            height: 50px;
            font-size: 18px;
          }
        }
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  .slide-verify-slider {
    margin: 0;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
